package com.topcent.tioxyc.controller;

import com.topcent.tioxyc.constants.RabbitConsts;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


/**
 * @author: 陈百万
 * @date: 2025/9/11 15:01
 * @Description: 费用单创建数据就添加到固定费、变动费
 */
@Slf4j
@RestController
public class CcFeiYongAddCostController {
    @Autowired
    private RabbitTemplate rabbitTemplate;

    private static final String SECRET = "KPIfb04KeXBOWkj3m9xDqKV9";

    @PostMapping("/feiYongAddCost")
    public String feiYongAddCost(@RequestParam("nonce") String nonce,
                           @RequestParam("timestamp") String timestamp,
                           @RequestHeader("x-jdy-signature") String signature,
                           @RequestBody String payload) {
        if (!validateSignature(nonce, payload, timestamp, signature)) {
            return "fail";
        }

        // 将 payload 发送到 RabbitMQ 队列
        rabbitTemplate.convertAndSend(RabbitConsts.FEIYONGADDCOST, payload);
        return "success";
    }

    private boolean validateSignature(String nonce, String payload, String timestamp, String signature) {
        String calculatedSignature = getSignature(nonce, payload, CcFeiYongAddCostController.SECRET, timestamp);
        return calculatedSignature.equals(signature);
    }

    private String getSignature(String nonce, String payload, String secret, String timestamp) {
        return DigestUtils.sha1Hex(nonce + ":" + payload + ":" + secret + ":" + timestamp);
    }

}
